class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> res = new ArrayList<Integer>();
        if (root == null) {
            return res;
        }
 
        Deque<TreeNode> stack = new LinkedList<TreeNode>();
        TreeNode prev = null;
        while (root != null || !stack.isEmpty()) {
            while (root != null) {//“一路向左”
                stack.push(root);
                root = root.left;
            }
            root = stack.pop();//取出栈顶，记住我们的原则是对栈顶进行处理
            if (root.right == null || root.right == prev) {//没有右孩子或者已经访问过
                res.add(root.val);
                prev = root;
                root = null;
            } else {//右孩子没被访问过
                stack.push(root);
                root = root.right;
            }
        }
        return res;
    }
}